<?php
namespace app\common\repositories\info;
use app\common\repositories\BaseRepository;
use app\common\dao\info\InfoDao as dao;
use app\common\repositories\lawyer\LawyerRepository;
use app\common\repositories\member\MemberSettingRepository;
use app\common\repositories\user\UserBalanceRepository;
use app\common\repositories\user\UserRepository;
use basic\services\MiniProgramService;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

/**
 * @mixin dao
 */
class InfoRepository extends BaseRepository
{
    const INFO_TYPE = [
      0 => '免费咨询',
      1 => '文书代写',
      2 => '合同审查',
      3 => '户籍调查',
      4 => '律师函',
      5 => '打官司',
      6 => '追欠款',
      7 => '咨询律师',
    ];


    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }


    public function getApiList($where,$page,$limit)
    {
        if($where['is_order'] == 1){
            $newWhere['type'] = [1,2,3,4,5,6];
            $newWhere['status'] = '';
        }else{
            $newWhere['status'] = $where['status'];
        }

        $newWhere['uid'] = request()->uid();

        $count = $this->dao->search($newWhere)->count();
        $list = $this->dao->search($newWhere)
            ->append(['questionContent'])
            ->order('i.info_id desc')->setOption('field',[])->field('i.*')->page($page,$limit)->select();

        return compact('count','list');
    }


    public function getLawyerApiLst($where,$page,$limit)
    {
        $count = $this->dao->search($where)->count();
        $list = $this->dao->search($where)
            ->append(['questionContent'])
            ->order('i.info_id desc')->setOption('field',[])->field('i.*')->page($page,$limit)->select();

        return compact('count','list');
    }


    public function getAdminLst($where,$page,$limit)
    {
        $count = $this->dao->search($where)->count();
        $list = $this->dao->search($where)
            ->order('i.info_id desc')->append(['city','typeName'])->setOption('field',[])->field('i.*')->page($page,$limit)->select();

        return compact('count','list');
    }



    public function createOrder($uid,$data)
    {

        try {
            $type = $data['type'];

            /**@var $make MemberSettingRepository**/
            $make = app()->make(MemberSettingRepository::class);
            Db::startTrans();
            $user = app()->make(UserRepository::class)->get($uid);

            $priceInfo = $make->getCasePrice($uid,$type);


            /*if($priceInfo['memberType'] != 0 && in_array($type,[0,7])){
                $price = 0;
            }else */
            if ($type == 0 && $data['use_free'] == 1){
                $canCount = systemConfig('user_can_free_count') ?: 0;
                $price = 0;
                if($canCount > $user->use_free_count){
                    app()->make(UserRepository::class)->incrNumberField($uid,'use_free_count');
                }else if($user->free_count > 0){
                    app()->make(UserRepository::class)->incrNumberField($uid,'free_count',-1);
                }else{
                    throw new ValidateException('免费次数不足，请邀请好友获取免费次数！');
                }
            } else {
                $price = $priceInfo['price'];
            }


            if($type == 7){
                $is_phone = input('is_phone',0);
                $data['is_phone'] = $is_phone;
            }


            $data['price'] = $price;
            $data['member_type'] = $priceInfo['memberType'];
            $data['order_no'] = getOrderSn('wx');
            $data['uid'] = $uid;
            $data['lawyer_id'] = $data['lawyer_id'] ?? 0;
            $data['status'] = 0;
            $data['pay_type'] = input('pay_type');

            $order = $this->dao->create($data);

            if($price <= 0){
                $payStatus = 0;
                $payConfig = [];
                $this->paySuccess($order['order_no']);
            }else if(input('pay_type') == 1){
                $payStatus = 0;
                $payConfig = [];
                if($user->balance < $price){
                    throw new ValidateException('余额不足');
                }
                /**@var $balanceMake UserBalanceRepository**/
                $balanceMake = app()->make(UserBalanceRepository::class);
                $balanceMake->recordBalance($uid,0,'info',self::INFO_TYPE[$type],$price);
                $this->paySuccess($order['order_no']);
            }else{
                $payStatus = 0;
                $payConfig = MiniProgramService::create()->jsPay($user->openid,$data['order_no'],$price*100,self::INFO_TYPE[$type],'info');;
            }
            Db::commit();

            return [
                'pay_status'=>$payStatus,
                'pay_config'=>$payConfig,
                'order_no'=>$data['order_no'],
                'price'=>$price
            ];
        }catch (\Exception $e){
            Db::rollback();
            if (!($e instanceof ValidateException)){
                Log::error('创建订单有误'.$e->getMessage().'|'.$e->getFile().'|'.$e->getLine());
            }
            throw new ValidateException($e->getMessage());
        }
    }


    public function refund($orderNo)
    {
        $order = $this->getWhere(['order_no'=>$orderNo,'uid'=>request()->uid()]);
        if(!$order)
            throw new ValidateException('订单不存在');
        if($order->status == -1)
            throw new ValidateException('订单已取消');

        if($order->status == 2)
            throw new ValidateException('取消失败，订单已在服务中');

        if($order->status == 3)
            throw new ValidateException('取消失败，订单已完成');

        if($order->price == 0){
            $order->save(['status'=>-1]);
            return success('取消成功');
        }

        $userInfo = request()->userInfo();
        Db::transaction(function ()use ($userInfo,$order){
            $save = ['status'=>-1];
            if($order->pay_type == 1){
                /**@var $balanceMake UserBalanceRepository**/
                $balanceMake = app()->make(UserBalanceRepository::class);
                $balanceMake->recordBalance($userInfo->uid,1,'refund','取消订单退款',$order->price);
            }else if($order->pay_type == 0){
                $refundNo = getOrderSn('R');
                $save['refund_no'] = $refundNo;
                MiniProgramService::create()->payRefund($order->order_no,$refundNo,$order->price*100,$order->price*100,'取消订单退款');
            }
            $order->save($save);
        });
        return success('取消成功');
    }


    public function setInfoStatus($id,$status)
    {
        $info = $this->dao->get($id);
        if($status == 2){
            $info->save(['status'=>2]);
        } else{
            $this->orderGone($id);
        }
    }



    public function paySuccess($orderNo)
    {
        Db::transaction(function () use ($orderNo){
            $order = $this->getWhere(['order_no'=>$orderNo]);
            if($order->status != 0){
                return;
            }

            if($order->type == 7 && $order->is_phone){
                return $order->save(['status'=>2,'is_paid'=>1,'auto_end_time'=>time() + 24*3600]);
            }

            $order->save(['status'=>1,'is_paid'=>1]);
        });
    }


    public function orderGone($id)
    {
        Db::transaction(function ()use ($id){
            $order = $this->dao->get($id);
            if($order->status == 0 || $order->status == 3 || $order->status == -1){
                return;
            }

            $user = app()->make(UserRepository::class)->get($order->uid);
            /**@var $balanceMake UserBalanceRepository**/
            $balanceMake = app()->make(UserBalanceRepository::class);
            $balanceMake->dealSpreadBrokerage($user->spread_uid,$order->info_id);

            $order->save(['status'=>3]);

            if($order->type == 7){
                $lawyer = app()->make(LawyerRepository::class)->get($order->lawyer_id);
                $rate = systemConfig('lawyer_income_percent') ? : 0;
                if($lawyer && $order->price > 0 && $rate > 0){
                    $lawyerPrice = bcmul($order->price,$rate,2);
                    if($lawyerPrice <= 0) return;
                    $balanceMake->recordBalance($lawyer->uid,1,'lawyer_service','服务收入',$lawyerPrice);
                }
            }
        });
    }


    public function getLawyerQuestionLst($where,$page,$limit)
    {
        if($where['type'] == 1){
            $newWhere['lawyer_id'] = $where['lawyer_id'];
            $newWhere['type'] = 7;
            $newWhere['status'] = [1,2,3];
        }else{
            $newWhere['type'] = 0;
            $newWhere['status'] = [1,2,3];
        }

        $count = $this->dao->search($newWhere)->count();
        $list = $this->dao->search($newWhere)
            ->with(['user'=>function($query){
                $query->field('uid,nickname,avatar');
            }])->append(['questionContent','questionCount'])
            ->order('i.info_id desc')->setOption('field',[])->field('i.uid,i.info_id,i.content,i.create_time,i.cate,i.type,i.price')->page($page,$limit)->select();

        return compact('count','list');
    }


    public function getQuestionIndexLst($where,$page,$limit)
    {
        $where['is_public'] = 1;
        $where['status'] = [2,3];
        $where['type'] = [0];
        $count = $this->dao->search($where)->count();
        $list = $this->dao->search($where)
            ->with(['user'=>function($query){
                $query->field('uid,nickname,avatar');
            }])->append(['questionContent','questionCount'])
            ->order('i.info_id desc')->setOption('field',[])->field('i.uid,i.info_id,i.content,i.create_time,i.cate,i.type,i.price')->page($page,$limit)->select();

        return compact('count','list');
    }
}